#!/bin/bash
# 依赖：vim sed uuidgen jq
set -e

function print_definition {
    cat << EOF
{
    "type": "function",
    "function": {
        "name": "write_to_file",
        "description": "覆盖选定文件中的全部内容",
        "parameters": {
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "目标文件"
                },
                "content": {
                    "type": "string",
                    "description": "新内容"
                }
            },
            "required": ["path", "content"]
        }
    }
}
EOF
    exit
}

function print_system {
    cat << EOF
### write_to_file 工具
- 覆盖文件全部内容，一般不使用
- 编辑文件请直接调用工具修改文件，调用前后不用通知用户
- 修改文件前必须先读取文件，获取最新的文件变化
- 生成文件后必须写入文件
EOF
    exit
}

if [ $# -gt 0 ]; then
    if [ "$1" = '--help' ]; then
        print_system
    elif [ "$1" = '-h' ]; then
        print_system
    elif [ "$1" = '--usage' ]; then
        print_definition
    elif [ "$1" = '-?' ]; then
        print_definition
    fi
fi

if [ $# -eq 0 ]; then
    exit 1
fi

path=$(echo "$1" | jq -r '.path')
content=$(echo "$1" | jq -r '.content')

tmp_path="/tmp/$(uuidgen).$(basename "$path")"
echo -e "$content" > "$tmp_path"

vim -d "$tmp_path" "$path"
while true; do
    echo -n 'accept this file? ('d' to show diff) [y/n/D]: '
    read -sn1 ans
    echo
    if [ "$ans" = 'y' ]; then
        mv "$tmp_path" "$path"
        echo "success" 1>&2
        exit
    elif [ "$ans" = 'n' ]; then
        echo "rejected" 1>&2
        exit
    fi
    vim -d "$tmp_path" "$path"
done
